﻿// ———————————————————————–
// <copyright file="DEProcessingService.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// DEProcessingService.cs - "Analyzes And Stores DE Messages"
// Project: "IC.NETSOA"- "DEProcessingSVC"
//
// Language:    C#, .NET 4.0
// Platform:    Windows 7, VS 2010
// Author:      Don McGarry The MITRE Corporation
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Xml.Linq;
using EDXLSharp;
using EDXLSharp.EDXLDELib;
using ICNETDAL;
using ICNETServices;

namespace DEProcessingSvc
{
  /// <summary>
  /// Contains a method for processing DE messages that have been sent to IC.NET
  /// </summary>
  public class DEProcessingService : IRoutingICNET
  {
    /// <summary>
    /// Processes a DE object and stores it to the database
    /// </summary>
    /// <param name="incomingDE">The DE object to be processed</param>
    [OperationBehavior(TransactionAutoComplete = true)]
        public void ProcessDE(EDXLDE incomingDE)
        {
          RouterClient client = new RouterClient();
          try
          {
            EDXLDEDal dal = new EDXLDEDal();
            EDXLDE storeDE = new EDXLDE(incomingDE.WriteToXML());

            for(int i=0; i< storeDE.SenderRole.Count;i++)
            {
              ///Need to remove the internal service stuff from the stored DE
              if (storeDE.SenderRole[i].ValueListURN == ICNETSOAConstants.ICNETServicesURI)
              {
                storeDE.SenderRole.RemoveAt(i);
                i--;
              }
              else if (storeDE.SenderRole[i].ValueListURN == ICNETSOAConstants.ICNETfedURI)
              {
                storeDE.SenderRole.RemoveAt(i);
                i--;
              }
            }

            foreach (ContentObject co in storeDE.ContentObjects)
            {
              if (co.ConsumerRole != null)
              {
                for (int i = co.ConsumerRole.Count - 1; i >= 0; i--)
                {
                  if (co.ConsumerRole[i].ValueListURN.EndsWith("Roles/Internal"))
                  {
                    co.ConsumerRole.RemoveAt(i);
                  }
                }
              }
            }

            switch (incomingDE.DistributionType)
            {
              case TypeValue.Cancel:
              case TypeValue.Update:
                dal.DeleteEmergencyMessageContainer(incomingDE.SenderID, incomingDE.DistributionID);
                break;
              default:
                break;
            }

            //don't add cancels to the database
            if (incomingDE.DistributionType != TypeValue.Cancel)
            {
              dal.AddToDB(storeDE);
            }
          }
          catch (Exception e)
          {
            ValueList servicerole = new ValueList();
            servicerole.ValueListURN = ICNETSOAConstants.ICNETServicesURI;
            servicerole.Value.Add(ICNETSOAConstants.ExceptionServiceNamespace);
            XNamespace ns = "http://tempuri.org";
            XElement xe = new XElement(ns + "Exception");
            xe.Add(new XElement("Message", e.Message));
            xe.Add(new XElement("StackTrace", e.StackTrace));
            xe.Add(new XElement("ErrorString", e.ToString()));
            ContentObject co = new ContentObject(ICNETSOAConstants.ICNETExceptionURI, new List<string>() { "Exception" });
            co.XMLContent = new XMLContentType();
            co.XMLContent.EmbeddedXMLContent.Add(xe);
            incomingDE.ContentObjects.Add(co);
            if (incomingDE.SenderRole.Count == 0)
            {
              incomingDE.SenderRole.Add(servicerole);
            }
            else
            {
              bool added = false;
              foreach (ValueList list in incomingDE.SenderRole)
              {
                if (list.ValueListURN == ICNETSOAConstants.ICNETServicesURI)
                {
                  list.Value.Clear();
                  list.Value.Add(ICNETSOAConstants.ExceptionServiceNamespace);
                  added = true;
                  break;
                }
              }

              if (!added)
              {
                incomingDE.SenderRole.Add(servicerole);
              }
            }

            client.ProcessDE(incomingDE);
          }
        }
    }
}
